//
// Created by mabinjie on 2024/10/28.
//

#ifndef VALIDATE_HPP
#define VALIDATE_HPP
#include <cstdint>

namespace protocol {

inline uint8_t get_checksum(const char* begin, const char *end) {
    uint8_t checksum = 0;
    for (int i = 0; begin+i != end; ++i) {
        checksum ^= *(begin+i);
    }
    return checksum;
}

inline bool checksum_is_valid(const char* begin, const char* end) {
    const uint8_t checksum = get_checksum(begin, end);
    return (checksum == *end);
}

inline bool escaper(const uint8_t to_encode, uint16_t& byte) {
    switch (to_encode) {
        case 0x7d: {
            byte = 0x7d01;
            break;
        }
        case 0x7e: {
            byte = 0x7d02;
            break;
        }
        default: {
            return false;
        }
    }
    return true;
}

inline bool reverse_escaper(void *buffer, uint8_t &res) {
    const auto buffer_ = static_cast<uint8_t*>(buffer);
    const uint16_t bytes = (*buffer_) << 8 | *(buffer_+1);
    if (bytes == 0x7d02) {
        res = 0x7e;
        return true;
    }
    if (bytes == 0x7d01) {
        res = 0x7d;
        return true;
    }
    res = bytes >> 8 & 0xff;
    return false;
}




}

#endif //VALIDATE_HPP
